// pages/my-houses/my-houses.js
import req from "../../../utils/request"
Page({
  data: {
    houses: [] // 初始化为空数组
  },

  onLoad() {
    this.loadHouses();
  },

  onShow(){
    this.loadHouses();
  },

  // 加载房屋数据
  loadHouses() {
    wx.showLoading({ title: "加载中..." });
    
    // 模拟API请求
    setTimeout( async() => {
      // 实际项目中这里应该是API请求
      const result = await req.get("/property/house/myResident")
      
      if (result.code === 200) {
        this.processHouseData(result.data);
      }
      
      wx.hideLoading();
    }, 500);
  },
  
  // 处理返回的房屋数据
  processHouseData(apiData) {
    const houses = apiData.map(item => {
      // 拼接完整的房间信息
      const roomInfo = `${item.buildingName}${item.unitName}${item.floor}${item.doorNumber}`;
      
      return {
        id: item.id,
        roomId: item.roomId,
        community: item.communityName,
        room: roomInfo,
        owner: item.owner ? item.owner.name : '未知', // 防止owner为空
        // 状态处理（0: 已通过, 其他状态根据实际需求设置）
        status: item.owner.status === 0 ? 'approved' : 'pending',
        statusText: item.owner.status === 0 ? '已通过' : '待审核',
        statusClass: item.owner.status === 0 ? 'status-approved' : 'status-pending',
        // 默认房屋设置（根据实际业务逻辑设置）
        isDefault: false
      };
    });
    
    // 设置第一项为默认房屋（示例逻辑，按业务需求调整）
    if (houses.length > 0) {
      houses[0].isDefault = true;
    }
    
    this.setData({ houses });
  },
  
  // 设置默认房屋（保持原逻辑）
  setDefault(e) {
    const { id } = e.currentTarget.dataset;
    
    wx.showModal({
      title: "提示",
      content: "确定要将该房屋设为默认吗？",
      success: (res) => {
        if (res.confirm) {
          this.handleSetDefault(id);
        }
      },
    });
  },
  
  // 处理设置默认房屋
  handleSetDefault(id) {
    wx.showLoading({ title: "设置中..." });
    
    // 模拟API请求
    setTimeout(() => {
      const houses = this.data.houses.map(house => ({
        ...house,
        isDefault: house.id === id
      }));
      
      this.setData({ houses });
      wx.hideLoading();
      wx.showToast({
        title: "设置成功",
        icon: "success",
      });
    }, 300);
  },
  
  // 其他方法保持不变
  onBindHouse() {
    wx.navigateTo({ url: "/pages/property/bind-house/bind-house" });
  },

  lookDetail(e){
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/property/resident-detail/resident-detail?id=${id}`,
    });
  },
  
  onPullDownRefresh() {
    this.loadHouses();
    setTimeout(() => wx.stopPullDownRefresh(), 1500);
  }
});